import React, { PureComponent } from 'react';
import { RouteComponentProps, withRouter } from 'react-router';
import Toast from '@/components/Toast';
import RSAEncrypt from '@/common/rsa-encrypt';
import md5 from 'md5';
import { getQueryString, isWXSQ, VALIDATES } from '@/common/utils';
import Services from './services';
import './index.less';
import { connect } from 'react-redux';

interface IConfirmProps extends RouteComponentProps {
  history: any;
  TXInfo: any;
  updateTXInfo: (payload: any) => Promise<any>;
  clearTXInfo: () => Promise<any>;
}

interface IConfirmState {
  phone: string;
  recordId: string;
  sideValidate: string;
  isSelected: boolean;
  isShowSilder: boolean;
  isDisabled: boolean;
}

const appId = '17aadeb2c21';
const scene = 'card-jwxd';
const token = 'cc17de2c703048d886ee6dab5d3625c4';

class Confirm extends PureComponent<IConfirmProps, IConfirmState> {
  timer: any;
  jdSlide: any;
  constructor(props: IConfirmProps) {
    super(props);
    this.state = {
      phone: '',
      recordId: getQueryString('recordId'),
      sideValidate: '',
      isSelected: false,
      isShowSilder: true,
      isDisabled: false
    };
  }

  componentDidMount() {
    const JSSDK = window['JSSDK'];
    JSSDK.Isv.isAppLogin((res: any) => {
      setTimeout(() => {
        if (String(res.data) === '0') {
          // 未登录状态
          const LOGIN_URL = isWXSQ()
            ? `https://wq.jd.com/pinbind/pintokenredirect?scope=1&biz=${process
                .env.REACT_APP_BIZ || 'activitycollector'}&url=`
            : `//plogin.m.jd.com/user/login.action?appid=${process.env
                .REACT_APP_APPID || 773}&returnurl=`;
          window.location.href =
            LOGIN_URL + encodeURIComponent(window.location.href);
        }
      }, 0);
    });

    this.initSilderCodeFunc();

    // 清空store数据
    this.props.clearTXInfo();
  }

  initSilderCodeFunc = () => {
    const _this = this;
    window['initJdSlide'] &&
      window['initJdSlide'](
        {
          id: 'card-resale-jwxd-jd-slide-id',
          appId: appId, //申请得到（必填）
          scene: scene, //用户自定义使用场景，便于按场景统计，需要找huwei111配置，不然影响通过率（必填）
          product: 'embed', // 验证码形式
          width: '300px',
          placeholder: '', //提示语（为空默认：向右滑动完成拼图）,
          successMess: '拼接成功', //验证成功提示语（为空默认：拼接成功）
          eventListener: true,
          getInstance: function(instance: any) {
            console.log(
              '%c [ instance ]',
              'font-size:13px; background:pink; color:#bf2c9f;',
              instance
            );
            this.jdSlide = instance;
          }
        },
        function(obj: any) {
          var validate = obj.getValidate(); //滑动成功 才返回validate,处理业务
          validate &&
            _this.setState({
              sideValidate: validate
            });
        }
      );
  };

  handleChangePhoneAction = (evt: any) => {
    const { value } = evt.target;
    let phone = value.replace(/\s/g, '').replace(/\D/g, '');
    this.setState(
      {
        phone
      },
      () => {
        this.props.updateTXInfo({
          phone
        });
      }
    );
  };

  handleBlurAction = (name: 'phone') => {
    if (!this.state[name]) {
      Toast.show(VALIDATES[name].empty);
      return false;
    }
    let isValidatePhone = VALIDATES[name].reg.test(this.state[name]);
    if (!isValidatePhone) {
      Toast.show(VALIDATES[name].error);
      return false;
    }
    return true;
  };

  validateParams = (phone: string) => {
    let validateObj = { phone };
    for (let key in validateObj) {
      if (!validateObj[key]) {
        Toast.show(VALIDATES[key].empty);
        return false;
      }
      let flag = VALIDATES[key].reg.test(validateObj[key]);
      if (!flag) {
        Toast.show(VALIDATES[key].error);
        return false;
      }
    }
    return true;
  };

  handleNextAtion = async () => {
    const { phone = '', sideValidate, isSelected } = this.state;
    let validateflag = this.validateParams(phone);
    if (!validateflag) return;
    if (!sideValidate) return Toast.show('请先完成拼图验证');
    if (!isSelected) return Toast.show('请先完成协议勾选');

    if (this.state.isDisabled) return;
    this.setState({
      isDisabled: true
    });

    // 滑块验证码滑块
    let imgCodeCheckRes = await Services.imgCodeCheck({
      appId,
      token,
      validate: sideValidate
    });
    if (!imgCodeCheckRes) {
      // 重置
      this.initSilderCodeFunc();
      this.setState({
        sideValidate: '',
        isDisabled: false
      });
      return;
    }

    let phoneNum = RSAEncrypt.encrypt(phone),
      t = new Date().getTime();

    const encStr = md5(`${phoneNum}${t}${RSAEncrypt.MD5KEY}`);
    let params = {
      phoneNum,
      t,
      encStr
    };
    let res = await Services.currentOperationState(params);
    if (!res) {
      this.initSilderCodeFunc();
      this.setState({
        sideValidate: '',
        isDisabled: false
      });
      return;
    }

    const { step } = res;

    if (![3, 4, 5].includes(Number(step))) {
      // 非上传完成 - 审核状态 都需要前置调用查用户身份，这个接口包含 - 不需要净网行动用户
      // 根据手机号查询姓名身份证接口 boss查询
      let userInfo = await Services.findUserName({
        phoneNumber: phoneNum
      });
      if (!userInfo || !Object.keys(userInfo).length) {
        this.initSilderCodeFunc();
        this.setState({
          sideValidate: '',
          isDisabled: false
        });
        return;
      }
      const { userName, certNum } = userInfo;
      this.props.updateTXInfo({
        userNameFromBoss: userName,
        certNumFromBoss: certNum
      });
    }

    this.setState({
      isDisabled: false
    });

    switch (String(step)) {
      // 0  未上传身份证照片 1 未上传活体； 2  未上传视频；
      case '0':
        this.props.history.push(`/auth${window.location.search}`);
        break;
      case '1':
        // 已实名，未活体，需要实名参数
        let { certNo, certName } = res || {};
        await this.props.updateTXInfo({
          certNoEnc: certNo,
          certNameEnc: certName
        });
        this.props.history.push(`/livingInfo${window.location.search}`);
        break;
      case '2':
        await this.props.updateTXInfo({
          certNoEnc: res.certNo,
          certNameEnc: res.certName
        });
        this.props.history.push(`/videoUpload${window.location.search}`);
        break;
      // 3  待审核 ；4  审核通过；5  审核不通过
      case '3':
      case '4':
      case '5':
        let { checkDesc } = res || {};
        await this.props.updateTXInfo({
          checkDesc: checkDesc
        });

        this.props.history.push(`/checkResult?type=${step}`);
        break;
      default:
        return;
    }
  };

  componentWillUnmount() {
    this.setState({
      isDisabled: false
    });
  }

  render() {
    const { phone = '', sideValidate, isSelected } = this.state;
    return (
      <div className="confirm-wrapper">
        <div className="confirm-wrapper-form">
          <div className="confirm-wrapper-form-item">
            <span className="confirm-wrapper-form-item-label">中国 (+86)</span>
            <input
              type="tel"
              maxLength={11}
              autoComplete="off"
              placeholder="请输入您的京东通信号码"
              className="confirm-wrapper-form-item-ipt tel"
              value={phone}
              onChange={this.handleChangePhoneAction}
              onBlur={() => this.handleBlurAction('phone')}
            />
          </div>

          {/* 滑块验证码 */}
          <div
            className={'confirm-wrapper-form-rccode JDValidate-wrap'}
            id="card-resale-jwxd-jd-slide-id"
          ></div>

          <div className="confirm-wrapper-protocol">
            <div className="confirm-wrapper-protocol-c">
              <div
                className={`confirm-wrapper-protocol-radio ${
                  isSelected ? 'confirm-wrapper-protocol-radio-active' : ''
                }`}
                onClick={() => {
                  this.setState({
                    isSelected: !this.state.isSelected
                  });
                }}
              ></div>
              <span className="confirm-wrapper-protocol-txt gx">请勾选</span>
              <span
                className="confirm-wrapper-protocol-txt lj"
                onClick={() => {
                  this.props.history.push('/protocol');
                }}
              >
                《法律责任风险提示告知书》
              </span>
            </div>
          </div>
          <div
            className={`confirm-wrapper-btn ${
              phone && sideValidate && isSelected ? '' : 'grey'
            }`}
            onClick={phone ? this.handleNextAtion : void 0}
          >
            下一步
          </div>
        </div>
      </div>
    );
  }
}

// @ts-ignore
const mapState = ({ CardReSold }) => ({
  TXInfo: CardReSold.TXInfo
});

// @ts-ignore
const mapDispath = ({ CardReSold }) => ({
  updateTXInfo: CardReSold.updateTXInfo,
  clearTXInfo: CardReSold.clearTXInfo
});

// @ts-ignore
export default connect(mapState, mapDispath)(withRouter(Confirm));
